import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jhtoast/jhtoast.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import '../refresh/refresh_mixin.dart';

import 'asset_preview_page.dart';
import 'asset_tool.dart';

class VolvoAssetController extends ChangeNotifier
    with VolvoRefreshMixin<AssetModel> {
  /// 已选中的资源
  List<AssetModel> selectedAssets = [];

  /// 资源路径列表
  List<AssetPathModel> paths = [];

  /// 当前资源模型
  AssetPathModel? _currentPathModel;

  /// 当前资源路径
  AssetPathEntity? _currentPath;

  /// 当前资源路径
  String currentPathName = "选择图片";

  /// 是否切换路径
  bool isSwitchingPath = false;

  /// 请求的资源类型
  late RequestType _type;

  /// 资源选择的最大数量
  late int _maxAssetCount;

  /// 视频最大长度
  late int _maxVideoLength;

  /// 资源选择回调
  ValueChanged<List<AssetEntity>>? _selectedCallback;

  VolvoAssetController({
    required LocalAssetType type,
    int maxAssetCount = 1,
    int maxVideoLength = 15,
    ValueChanged<List<AssetEntity>>? callback,
  }) {
    _maxAssetCount = maxAssetCount;
    _maxVideoLength = maxVideoLength;
    _type = type == LocalAssetType.common
        ? RequestType.common
        : type == LocalAssetType.image
            ? RequestType.image
            : RequestType.video;
    _selectedCallback = callback;
    _getPaths();
  }

  /// 获取资源路径列表
  void _getPaths() async {
    /***
     * 获取相册/文件夹列表。
     * hasAll：设置为true，获取包含根专辑(通常命名为“Recent”)的专辑列表。
     * onlyAll：设置为true，只获取列表中的根相册。
     * type：类型。
     * filterOption：过滤选项。
     */
    List<AssetPathEntity> assetPath = await PhotoManager.getAssetPathList(type: _type);
    debugPrint("assetPath----$assetPath");
    for (int i = 0;  i < assetPath.length; i++) {
      AssetPathEntity p = assetPath[i];
      int count = await p.assetCountAsync;
      if (count != 0) {
        List<AssetEntity> assets = await p.getAssetListPaged(page: 0, size: 1);
        AssetPathModel pathModel = AssetPathModel(isSelected: i == 0 ? true : false, assetCount: count, pathEntity: p, assetEntity: assets.first);
        paths.add(pathModel);
      }
    }
    if (paths.isNotEmpty) {
      _currentPathModel = paths.first;
      _currentPath = _currentPathModel!.pathEntity;
      currentPathName = _currentPath?.name ?? "";
      await getAssetsFromCurrentPath();
    }
  }

  /// 从当前已选路径获取资源列表
  Future<void> getAssetsFromCurrentPath() async {
    if (paths.isEmpty && _currentPath != null) {
      return;
    }
    if (paths.isNotEmpty && _currentPath == null) {
      return;
    }
    if (paths.isEmpty || _currentPath == null) {
      return;
    }

    // callRefresh();
    requestList(1);
  }

  @override
  Future<List<AssetModel>> requestList(int page) async {
    if (page == 1) {
      dataList.clear();
    }
    List<AssetModel> temps = [];
    List<AssetEntity>? tempAssets =
        await _currentPath?.getAssetListPaged(page: page - 1, size: 80);
    // debugPrint("当前页：$page，返回图片数量:${tempAssets?.length}");
    if (tempAssets != null) {
      for (var entity in tempAssets) {
        AssetModel model = AssetModel(isSelected: false, assetEntity: entity);
        for (AssetModel m in selectedAssets) {
          if (m.assetEntity.id == model.assetEntity.id) {
            model.isSelected = true;
          }
        }
        temps.add(model);
      }
    }
    int? assetCount = await _currentPath?.assetCountAsync;
    debugPrint("总数：$assetCount");
    if (assetCount != null) {
      hasNext = assetCount > dataList.length;
    }

    if (page == 1) {
      dataList.addAll(temps);
      notifyListeners();
    }
    return temps;
  }

  @override
  void onRequestComplete() {
    notifyListeners();
  }

  void resultBack(BuildContext context) {
    List<AssetEntity> temps = [];
    for (var entity in selectedAssets) {
      temps.add(entity.assetEntity);
    }
    _selectedCallback?.call(temps);
    Navigator.pop(context);
  }

  void clickAsset(BuildContext context, {required AssetModel selectModel}) {
    AssetEntity assetEntity = selectModel.assetEntity;
    if (assetEntity.duration > _maxVideoLength) {
      // HudUtil.toast("视频最大支持$_videoLength秒");
      return;
    }
    // 判断是否超过最大数
    if (!selectModel.isSelected && selectedAssets.length == _maxAssetCount) {
      // HudUtil.toast("最多选择$_limit张");
      JhToast.showText(context,msg:'最多选择$_maxAssetCount张图片',);
      return;
    }

    selectModel.isSelected = !selectModel.isSelected;
    if (selectModel.isSelected) {
      selectedAssets.add(selectModel);
    } else {
      selectedAssets.remove(selectModel);
    }
    notifyListeners();
  }

  void switchingPath() {
    isSwitchingPath = !isSwitchingPath;
    notifyListeners();

  }

  void selectedPath(AssetPathModel pathModel) {
    isSwitchingPath = false;
    if (_currentPathModel?.pathEntity.id == pathModel.pathEntity.id) {
      notifyListeners();
      return;
    }
    _currentPathModel?.isSelected = false;
    pathModel.isSelected = true;
    _currentPathModel = pathModel;
    _currentPath = pathModel.pathEntity;
    currentPathName = _currentPath?.name ?? "";
    refreshController=RefreshController(initialRefresh: false);
    requestList(1);
  }

  void preview(BuildContext context, int index) async {
    List<AssetModel> assets = await Navigator.push(
      context,
      CupertinoPageRoute(
        builder: (context) => VolvoAssetPreviewPage(
          dataList: dataList,
          selectedAssets: selectedAssets,
          currentIndex: index,
          maxAssetCount: _maxAssetCount,
          maxVideoLength: _maxVideoLength,
          // selectedCallback: (List<AssetModel> assets) {
          //   selectedAssets.clear();
          //   selectedAssets.addAll(assets);
          // },
        ),
      ),
    );
    // selectedAssets.removeWhere((e) => e.isSelected == false);
    selectedAssets.clear();
    selectedAssets.addAll(assets);
    notifyListeners();
  }
}

class AssetPathModel {
  bool isSelected;
  int assetCount;
  AssetPathEntity pathEntity;
  AssetEntity assetEntity;

  AssetPathModel({required this.isSelected, required this.assetCount, required this.pathEntity, required this.assetEntity});
}

class AssetModel {
  bool isSelected;
  AssetEntity assetEntity;

  AssetModel({required this.isSelected, required this.assetEntity});

  AssetModel copyWith({
    bool? isSelected,
    AssetEntity? assetEntity,
  }) =>
      AssetModel(
        isSelected: isSelected ?? this.isSelected,
        assetEntity: assetEntity ?? this.assetEntity,
      );
}
